package top.onedream.buildsmallsoftware.service.impl

import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.support.TransactionSynchronizationManager
import org.springframework.util.ObjectUtils
import top.onedream.buildsmallsoftware.cfg.exception.CustomException
import top.onedream.buildsmallsoftware.enums.ExceptionEnum
import top.onedream.buildsmallsoftware.model.user.Role
import top.onedream.buildsmallsoftware.model.user.User
import top.onedream.buildsmallsoftware.repo.RoleRepository
import top.onedream.buildsmallsoftware.repo.UserRepository
import top.onedream.buildsmallsoftware.service.UserService


@Service
class UserServiceImpl(
    private val userRepository: UserRepository,
    private val roleRepository: RoleRepository
) : UserService {
    override fun getCurrentUser(id: Long?, page: Int, size: Int, desc: Boolean): List<User?> =
        if (!ObjectUtils.isEmpty(id)) {
            listOf(userRepository.findByIdOrNull(id!!))
        } else {
            val sortOrder = if (desc) "desc" else "asc"
            val pageable: Pageable =
                PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortOrder), "username"))
            val findAll = userRepository.findAll(pageable)
            findAll?.toList() ?: listOf()
        }

    override fun getUserByUsernameAndAge(username: String?, age: Int?): List<User> =
        userRepository.findUsersByUsernameAndAge(username, age)

    @Transactional(rollbackFor = [Exception::class])
    override fun saveAUser(user: User): Long =
        userRepository.save(user).id ?: -1


    override fun getUserByUsername(username: String): User? =
        userRepository.findByUsername(username)


    override fun updateUserRole(roleId: Long?, roleName: String?, userId: Long): Long? =
        if (!ObjectUtils.isEmpty(roleId)) {
            val orElse = roleRepository.findById(roleId!!).orElse(null)
            orElse?.let {
                userRepository.save(User(id = userId, role = it))
            }?.id
        } else if (!ObjectUtils.isEmpty(roleName)) {
            val findRoleByRoleName = roleRepository.findRoleByRoleName(roleName)
            findRoleByRoleName?.let {
                userRepository.save(User(id = userId, role = it))
            }?.id
        } else {
            null
        }


}